// pages/ranking/ranking.js
import $ from '../../utils/tool'
import log from '../../utils/log'
import userModel from '../../model/user'
import router from '../../utils/router'
const db = wx.cloud.database()
const _ = db.command
const app = getApp()

Page({
  data: {
    activeIndex: '-1',
    listHeight: app.globalData.screenHeight - app.globalData.CustomBar - 62,
    rankingList: [],
    myInfo: {},
    hasUserInfo: false
  },

  onShow() {
    getApp().globalData.logs = $.storage.get('logs')
    // 从缓存中获取登录信息
    let hasUserInfo = $.storage.get('hasUserInfo')
    let userInfo = $.storage.get('userInfo')
    let openid = $.storage.get('openid')
    userModel.getUserInfo(openid).then(res => {
      userInfo = res.data[0]
      $.storage.set('userInfo', userInfo)
    })
    if( hasUserInfo == true ) {
      getApp().globalData.hasUserInfo = hasUserInfo
      getApp().globalData.openid = openid
      getApp().globalData.userInfo = userInfo
      this.setData({hasUserInfo, userInfo})
    }
    let activeIndex = this.data.activeIndex== '-1' ? 0 : this.data.activeIndex
    const obj = { currentTarget: {dataset: {index: String(activeIndex ? activeIndex : 0)}}}
    this.tapRanking(obj)
  },
  
  // 选择好友榜或挑战榜
  tapRanking(e) {
    const { currentTarget: { dataset: {index}}} = e //即index = e.currentTarget.dataset.index
    const { data: { activeIndex } } = this 
    if( activeIndex != index) {
      this.setData({
        activeIndex: index
      })
      if (index == 1) { // 选择挑战榜
        this.getChallengeRank() 
      } else if(index == 0){ // 选择好友榜
        this.getFriendRank()
      }
    } 
  },

  async getFriendRank() {
    try {
      $.loading('加载中...')
      let userInfo = app.globalData.userInfo
      userInfo = userModel.updateUserFocus(userInfo) //传回带focus的userInfo
      $.storage.set('userInfo', userInfo)
      let friendList = userInfo.friendList
      if(userInfo._id){ //登录
        const { list } = await userModel.getFriendRank(friendList)
        this.setData({ rankingList: list })
      }else { //未登录
        this.setData({ rankingList: []})
      }
      $.hideLoading()
    }catch(error) {
      log.error(error)
      this.selectComponent('#errorMessage').show('获取失败, 请重试...', 2000, () => { router.toHome() })
    }
  },
  
  async getChallengeRank() {
    try {
      $.loading('加载中...')
      let userInfo = app.globalData.userInfo
      userModel.updateUserFocus(userInfo) //传回带focus的userInfo
      $.storage.set('userInfo', userInfo)
      const res = await userModel.getChallengeRank()
      const { list, myInfo } = res
      this.setData({ rankingList: list, myInfo })
      $.hideLoading()
    } catch (error) {
      log.error(error)
      this.selectComponent('#errorMessage').show('获取失败, 请重试...', 2000, () => { router.toHome() })
    }
  },

  // 好友管理
  manageFriend() {
    // console.log(app.globalData.hasUserInfo)
    if (app.globalData.hasUserInfo) {
      wx.navigateTo({
        url: '/pages/friend/friend?index=0'
      })
    }
    else {
      wx.showToast({
        title: '请先前往设置登录帐号',
        icon: 'none',
        success() {
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/setting/setting',
            })
          }, 1500)
        }
      })
    }
  }
})